<!--
 * @Descripttion:  
 * @version:  
 * @Author: chenxf
 * @Date: 2023-03-08 09:41:30
-->
<template>
  <div class="user-select-cotainer">
    <a-input-group compact>
      <a-input
        :value="texts.join()"
        placeholder="请选择"
        style="width:calc(100% - 80px)"
        readOnly
        @change="() => {}"
        @click="showTable"
      ></a-input>
      <a-button @click="showTable" style="width:80px" type="primary">选择</a-button></a-input-group
    >
    <a-modal
      :title="'用户选择'"
      :key="'userSelect'"
      :bodyStyle="bodyStyle"
      :width="modalWidth"
      :visible="visible"
      v-if="visible"
      destroyOnClose
      :footer="null"
      @cancel="hideTable"
    >
      <div>
        <div class="header">
          <a-form-model :layout="'inline'">
            <a-form-model-item label="租户">
              <a-select
                v-model.trim="queryParam.tenantId"
                @change="search"
                :options="tenantsOpitons"
                style="min-width:200px;"
              />
            </a-form-model-item>
            <a-form-model-item label="姓名">
              <a-input v-model.trim="queryParam.realname" @keydown.enter="search" />
            </a-form-model-item>
            <a-form-model-item label="账号">
              <a-input v-model.trim="queryParam.username" @keydown.enter="search" />
            </a-form-model-item>
            <a-form-model-item label="组织名称">
              <a-input v-model.trim="queryParam.tenantName" @keydown.enter="search" />
            </a-form-model-item>
            <a-form-model-item label="手机号">
              <a-input v-model.trim="queryParam.phone" @keydown.enter="search" />
            </a-form-model-item>
          </a-form-model>
          <div class="header-search">
            <a-button type="primary" @click="search">搜索</a-button>
          </div>
        </div>

        <div class="table-container" :style="{ height: tableHeight }">
          <a-table
            bordered
            :data-source="dataSource"
            :columns="columns"
            :pagination="pagination"
            rowKey="username"
            :row-selection="rowSelection"
            size="small"
            :loading="isLoading"
            @change="handleTableChange"
            :customRow="customRow"
          >
          </a-table>
        </div>
        <div class="footer">
          <a-button type="danger" @click="cleanAll" v-if="selectedRowKeys.length" ghost>清空</a-button>
          <a-button type="primary" @click="submitEvent">选择({{ selectedRowKeys.length }})</a-button>
          <a-button @click="hideTable">关闭</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { httpAction, getAction, postAction, putAction, deleteAction } from '@/api/manage'
import { TENANT_ID } from '@/store/mutation-types'
import Vue from 'vue'
export default {
  name: 'userSelect',
  components: {},
  props: {
    showInput: {
      type: Boolean,
      default: true
    },
    value: {
      type: String
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      userName: '',
      visible: false,
      modalWidth: 1300,
      bodyStyle: {
        padding: '20px',
        top: 0,
        height: window.innerHeight - 80 + 'px'
      },
      tableHeight: window.innerHeight - 280 + 'px',
      dataSource: [],
      queryParam: {
        realname: '',
        tenantName: '',
        phone: '',
        username: '',
        tenantId: ''
      },
      columns: [],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true
      },
      userUrl: '/auth/users/tenants/child-users',
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'realname'
        },
        {
          title: '账号',
          align: 'center',
          dataIndex: 'username'
        },

        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'tenantName'
        },
        {
          title: '部门',
          align: 'center',
          dataIndex: 'departNames'
        },
        {
          title: '手机号',
          align: 'center',
          dataIndex: 'phone'
        }
      ],
      selectedRowKeys: [],
      texts: [],
      userDict: {},
      isLoading: false,
      tenantsOpitons: []
    }
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection
      }
    }
  },
  watch: {
    value: {
      handler() {
        this.transfromText()
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.queryParam.tenantId = Vue.ls.get(TENANT_ID)
    this.getUserData()
    this.getTenants()
    this.transfromText()
  },
  methods: {
    customRow(record) {
      return {
        on: {
          click: event => {
            if (this.selectedRowKeys.includes(record.username)) {
              let index = this.selectedRowKeys.indexOf(record.username)
              this.selectedRowKeys.splice(index, 1)
            } else {
              this.selectedRowKeys.push(record.username)
            }
          }
        }
      }
    },
    getTenants() {
      const postData = {
        ids: this.queryParam.tenantId
      }
      getAction('/auth/tenants', postData).then(res => {
        this.tenantsOpitons = res.result.rows.map(i => {
          return { value: i.id, label: i.name }
        })
      })
    },
    showTable() {
      this.visible = true
    },
    hideTable() {
      this.visible = false
    },
    search() {
      this.pagination.pageNo = 1
      this.getUserData()
    },
    getUserData() {
      const postData = {
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        ...this.queryParam
      }
      this.isLoading = true
      getAction(this.userUrl, postData).then(res => {
        this.dataSource = res.result.rows
        this.pagination.total = res.result.totalRows
        this.isLoading = false
      })
    },
    onSelectChange(keys) {
      this.selectedRowKeys = keys
    },
    onSelection(keys) {
      this.selectedRowKeys = keys
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination)
      const pager = { ...this.pagination }
      pager.pageNo = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.getUserData()
    },
    change() {
      this.$emit('change', this.selectedRowKeys.join())
    },
    submitEvent() {
      this.$emit('change', this.selectedRowKeys.join())
      this.hideTable()
    },
    transfromText() {
      if (this.value) {
        this.selectedRowKeys = this.value && this.value.split(',')
        this.getUserByIdAll(this.selectedRowKeys.join())
          .then(res => {
            this.texts = res
          })
          .catch(() => {
            this.texts = this.selectedRowKeys
          })
      } else {
        this.selectedRowKeys = []
        this.texts = []
      }
    },
    getUserByIdAll(values) {
      return new Promise(resolve => {
        getAction('/auth/users', {
          username: values
        }).then(res => {
          if (res.success) {
            resolve(
              res.result.rows.map(i => {
                return i.realname
              })
            )
          } else {
            resolve(values)
          }
        })
      })
    },
    cleanAll() {
      this.selectedRowKeys = []
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-modal {
  top: 0;
  padding: 0;
}
.header {
  padding-bottom: 10px;
  .header-search {
    padding-top: 10px;
  }
}
.table-container {
  overflow: auto;
}
.footer {
  text-align: center;
  margin: auto;
  padding-top: 10px;
  button {
    margin-right: 10px;
  }
}
</style>
